import { configureStore, combineReducers } from '@reduxjs/toolkit';
import authSlice from './slices/authSlice';
import signInSlice from './slices/signInSlice';

// 创建根reducer
const rootReducer = combineReducers({
  auth: authSlice,
  signIn: signInSlice,
});

// 安全地存储到localStorage
const safeSetItem = (key, value) => {
  try {
    if (value === null || value === undefined) {
      localStorage.removeItem(key);
    } else {
      localStorage.setItem(key, typeof value === 'string' ? value : JSON.stringify(value));
    }
  } catch (err) {
    console.error('Error saving to localStorage:', err);
  }
};

// 安全地从localStorage中获取
const safeGetItem = (key, parse = false) => {
  try {
    const value = localStorage.getItem(key);
    if (value === null) return null;
    return parse ? JSON.parse(value) : value;
  } catch (err) {
    console.error('Error reading from localStorage:', err);
    return null;
  }
};

// 创建持久化中间件
const localStorageMiddleware = store => next => action => {
  const result = next(action);
  
  // 当认证状态改变时，保存到localStorage
  if (
    action.type === 'auth/loginStudent/fulfilled' ||
    action.type === 'auth/getUserInfo/fulfilled' ||
    action.type === 'auth/logout' ||
    action.type === 'auth/logoutStudent/fulfilled' ||
    action.type === 'auth/logoutStudent/rejected'
  ) {
    const authState = store.getState().auth;
    
    // 处理登录成功的情况
    if (action.type === 'auth/loginStudent/fulfilled' && action.payload) {
      const { token, student } = action.payload;
      
      if (token) {
        safeSetItem('token', token);
      }
      
      if (student) {
        safeSetItem('user', student);
      }
    }
    // 处理其他认证状态变化
    else if (authState.token) {
      safeSetItem('token', authState.token);
      safeSetItem('user', authState.user);
    } else {
      safeSetItem('token', null);
      safeSetItem('user', null);
    }
  }
  
  return result;
};

// 创建store
export const store = configureStore({
  reducer: rootReducer,
  middleware: (getDefaultMiddleware) => 
    getDefaultMiddleware().concat(localStorageMiddleware),
  // 预加载状态，从localStorage恢复
  preloadedState: {
    auth: {
      user: safeGetItem('user', true),
      token: safeGetItem('token'),
      isAuthenticated: !!safeGetItem('token'),
      loading: false,
      error: null,
    }
  }
});

// 导出一个辅助函数，用于检查和恢复认证状态
export const checkAuthState = () => {
  const token = safeGetItem('token');
  const user = safeGetItem('user', true);
  
  return {
    token,
    user,
    isAuthenticated: !!token
  };
};

export default store;